package com.example.demo.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.example.demo.pojo.User;

@Service
public class UserService {
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;  //ribbon 的负载均衡器
	
	public List<User> getUser(){
		//选择调用的服务的名称
		//ServiceInstance 封装了服务的基本信息，如 IP，端口
		ServiceInstance si = this.loadBalancerClient.choose("server-produce");
		//拼接访问的URL
		StringBuffer sb = new StringBuffer();
		sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/user");
		
		RestTemplate restTemplate = new RestTemplate();
		
		ParameterizedTypeReference<List<User>> type = new ParameterizedTypeReference<List<User>>() {};
		
		ResponseEntity<List<User>> response =restTemplate.exchange(sb.toString(),HttpMethod.GET,null,type);
		List<User> list = response.getBody();
		return list;
		
	}
}
